package com.gapp.king.web.server;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import com.gapp.king.web.client.NotLoggedInException;
import com.gapp.king.web.client.StockService;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class StockServiceImpl extends RemoteServiceServlet implements
		StockService {

	private static final Logger log = Logger.getLogger(StockServiceImpl.class.getName());
	private static final PersistenceManagerFactory PMF = 
		JDOHelper.getPersistenceManagerFactory("transactions-optional");
	@Override
	public void addStock(String symbol) throws NotLoggedInException {
		
		checkLoggedin();
		PersistenceManager pm = getPersitenceManager();
		try
		{
			pm.makePersistent(new Stock(getUser(),symbol));
		}
		finally
		{
			pm.close();
		}

	}

	@Override
	public String[] getStocks() throws NotLoggedInException {
		checkLoggedin();
		PersistenceManager pm = getPersitenceManager();
		List<String> symbols = new ArrayList<String>();
		
		try
		{
			Query q = pm.newQuery(Stock.class,"user == u");
			q.declareParameters("com.google.appengine.api.users.User u");
			q.setOrdering("createDate");
			List<Stock> stocks = (List<Stock>) q.execute(getUser());
		    for (Stock stock : stocks) 
		    {
		        symbols.add(stock.getSymbol());
		    }
		}
		finally
		{
			pm.close();
		}
		
		return (String [])symbols.toArray(new String[0]);
	}

	@Override
	public void removeStock(String symbol) throws NotLoggedInException {
		checkLoggedin();
		PersistenceManager pm = getPersitenceManager();
		try
		{
			long deleteCount = 0;
			Query q = pm.newQuery(Stock.class, "user == u");
			q.declareParameters("com.google.appengine.api.users.User u");
			List<Stock> stocks = (List<Stock>) q.execute(getUser());
			
			for ( Stock stock : stocks)
			{
				if ( symbol == stock.getSymbol())
				{
					deleteCount++;
					pm.deletePersistent(stock);
				}
			}
			
			if (deleteCount != 1)
			{
				log.warning("remove stock deleted "+deleteCount + "stocks!");
			}
		}
		finally
		{
			pm.close();
		}

	}
	
	
	private void checkLoggedin() throws NotLoggedInException
	{
		if ( getUser() == null)
			throw new NotLoggedInException("User not logged in!");
	}
	
	private User getUser()
	{
		UserService userService = UserServiceFactory.getUserService();
		return userService.getCurrentUser();
	}
	
	private PersistenceManager getPersitenceManager()
	{
		return PMF.getPersistenceManager();
	}

}
